package com.letv.android.client.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import com.ledim.activity.MainActivity;
import com.ledim.bean.LedimChoiceCardBean;
import com.ledim.bean.LedimEpisodeBean;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.db.LedimDBUtils;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.letv.android.client.LetvSDK;
import com.letv.android.client.album.controller.AlbumController;
import com.letv.android.client.album.controller.AlbumErrorTopController;
import com.letv.android.client.album.controller.AlbumGestureController;
import com.letv.android.client.album.controller.AlbumLoadController;
import com.letv.android.client.album.controller.AlbumNetChangeController;
import com.letv.android.client.album.controller.AlbumPlayAdController;
import com.letv.android.client.album.controller.AlbumPlayVipTrailController;
import com.letv.android.client.album.controller.AlbumRecommendController;
import com.letv.android.client.album.controller.LongWatchController;
import com.letv.android.client.constant.FragmentConstant;
import com.letv.android.client.controller.AlbumGestureObservable;
import com.letv.android.client.controller.ScreenObservable;
import com.letv.android.client.episode.PlayAlbumController;
import com.letv.android.client.episode.fragment.TabsFragment;
import com.letv.android.client.fragment.AlbumBaseControllerFragment;
import com.letv.android.client.fragment.AlbumFullControllerFragment;
import com.letv.android.client.fragment.AlbumHalfControllerFragment;
import com.letv.android.client.fragment.AlbumPlayFragment;
import com.letv.android.client.meditor.VideoControllerMeditor;
import com.letv.android.client.utils.AlbumLaunchUtils;
import com.letv.android.client.view.AlbumPlayContainView;
import com.letv.android.young.client.R;
import com.letv.business.flow.LeMPSession.PlayStateableHandler;
import com.letv.business.flow.PlayFlowEvents.FetchMetaEvent;
import com.letv.business.flow.album.AlbumFlowUtils;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.business.flow.album.AlbumPlayFlowObservable;
import com.letv.business.flow.album.PlayObservable;
import com.letv.business.flow.album.model.AlbumPlayInfo;
import com.letv.business.flow.play.PlayStatisticsUtils;
import com.letv.core.bean.VideoBean;
import com.letv.core.constant.PlayConstant;
import com.letv.core.network.volley.Volley;
import com.letv.core.network.volley.VolleyRequest;
import com.letv.core.network.volley.VolleyRequestQueue.RequestFilter;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.StringUtils;
import com.letv.core.utils.UIsUtils;

import com.letv.tracker2.agnes.VideoPlay;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

/**
 * 点播页
 *
 * @author zhuqiao
 */
public class AlbumPlayActivity extends LetvBaseActivity {

    public static final String MFINISHSELFACTION = "mFinishSelfAction";
    private static final int POSITIVE = 180001;
    private static final int TV = 181031;
    /**
     * 打开方式(用来区别播放不同的视频)
     **/
    public int mLaunchMode;
    /**
     * 是否是4d视频
     **/
    public boolean mIs4dVideo;

    /**
     * 播放器fragment
     **/
    private AlbumPlayFragment mAlbumPlayFragment;
    /**
     * 半屏播放控制器fragment
     **/
    private AlbumHalfControllerFragment mHalfControllerFragment;
    /**
     * 全屏播放控制器fragment
     **/
    private AlbumFullControllerFragment mFullControllerFragment;
    /**
     * Tabs签fragment
     **/
    private TabsFragment mTabsFragment;

    /**
     * videoView和videoController交互中介者
     **/
    private VideoControllerMeditor mVideoControllerMeditor;

    /**
     * 点播流程
     **/
    private AlbumPlayFlow mPlayAlbumFlow;

    /**
     * 点播流程状态机handler
     **/
    private PlayStateableHandler playStateableHandler;

    /**
     * 点播流程变化观察者
     **/
    private AlbumPlayFlowObservable mFlowObservable = new AlbumPlayFlowObservable();
    /**
     * 播放过程中状态变化观察者
     **/
    private PlayObservable mPlayObservable;
    /**
     * 手势状态变化观察者
     **/
    private AlbumGestureObservable mGestureObservable = new AlbumGestureObservable();
    /**
     * 横竖屏切换观察者
     **/
    private ScreenObservable mScreenObservable = new ScreenObservable();
    /**
     * 手势控制器
     **/
    private AlbumGestureController mGestureController;
    /**
     * 广告控制器
     **/
    private AlbumPlayAdController mPlayAdController;
    /**
     * vip试看工具类
     **/
    private AlbumPlayVipTrailController mVipTrailController;
    /**
     * 控制工具类(返回、切换横竖屏)
     **/
    private AlbumController mController;
    /**
     * 网络切换提示布局控制器
     **/
    private AlbumNetChangeController mNetChangeController;
    /**
     * 覆盖videoview时，显示的返回、标题、全半屏切换控制器
     **/
    private AlbumErrorTopController mTopController;
    /**
     * 推荐提示控制器
     **/
    private AlbumRecommendController mRecommendController;
    /**
     * 长时间观看控制器
     **/
    private LongWatchController mLongWatchController;
    /**
     * loadlayout控制器
     **/
    private AlbumLoadController mLoadController;
    /**
     * 底部tab控制器
     **/
    private PlayAlbumController playAlbumController;

    /**
     * 是否正在显示长时间观看
     **/
    public static boolean sIsShowingLongwatch = false;
    /**
     * 用户如果不是手动的点击暂停，那么就不要有广告的弹出
     **/
    public static boolean sIsBlockPause = false;
    public static boolean sIsFromDownload = false;
    public static boolean sIsFromCollection = false;
    public static boolean sIsFromDobiChannel = false;

    private FrameLayout mBottomFrame, mFloatFrame;

    private boolean mHasStartFlowOnStart = false;

    private boolean mIsLoadData = true;
    private boolean mFromPushMsg;//从个推消息跳转而来

    private View mAlbumsLayout;
    private View mButtonLayout;
    private View mAddTagLayout;
    private int mPlayVid = -1;

    private LedimChoiceCardBean mCard;

    private BroadcastReceiver mFinishSelf = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent intent) {
            if (intent.getAction().equals("mFinishSelfAction")) {
                finish();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.letv_activity_play_album);

        LetvSDK.getInstance().init();

        initMParams();
        AlbumLaunchUtils.setIsPidIn(getIntent());
        initDataFromIntent(getIntent());
        init();
        initFragments();

        IntentFilter mfFilter = new IntentFilter(MFINISHSELFACTION);
        registerReceiver(mFinishSelf, mfFilter);

        playStateableHandler = new PlayStateableHandler(this);
        playStateableHandler.onCreate(savedInstanceState);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent == null) {
            return;
        }
        //initDataFromIntent(intent);
        //initWithIntent(intent);
        //AlbumLaunchUtils.setIsPidIn(getIntent());
        //initWindow();
        finish();
        Intent tempIntent = new Intent(getApplicationContext(), AlbumPlayActivity.class);
        if (intent.getExtras() != null) {
            tempIntent.putExtras(intent.getExtras());
        }
        tempIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplicationContext().startActivity(tempIntent);
        return;
        //if (mPlayAlbumFlow != null) {
        //    mPlayAlbumFlow.format();
        //}
        //
        //startFlow(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 保证fragment都初始化完成
        if (!mHasStartFlowOnStart) {
            mHasStartFlowOnStart = true;
            startFlow(getIntent());
        }
        initWindow();
        UIsUtils.enableScreenAlwaysOn(this);
        // 统计-后台返回
        if (mPlayAlbumFlow != null && mHomeKeyEventReceiver != null &&
                mHomeKeyEventReceiver.isHomeClicked()) {
            mPlayAlbumFlow.getPlayInfo().mReplayType = 3;
            mPlayAlbumFlow.getPlayInfo().mIsAfterHomeClicked = true;
            boolean hasFinishAd =
                    (mPlayAdController != null && mPlayAdController.getAdFragment().isFinishAd());
//            mPlayAlbumFlow.statisticsLaunchAndInit(hasFinishAd);
            PlayStatisticsUtils.statisticsLaunchAndInit(mContext,getFlow(),hasFinishAd);
        }

        playStateableHandler.onResume();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mController.onResume();
        mGestureController.onResume();
        mController.initDefaultSensor(); // 初始化陀螺仪---重力感应
        mAlbumPlayFragment.onResume();
        mAlbumPlayFragment.callAdsPlayInterface(AlbumPlayFragment.ON_ACTIVITY_RESUME, false);
        // 收集点击图片播放视频到此处所用的时间
        if (mPlayAlbumFlow != null) {
            mPlayAlbumFlow.getPlayInfo().mTimeFromClickToPlayOnResume =
                    StringUtils.staticticsLoadTimeInfoFormat(
                            System.currentTimeMillis() - StatisticsUtils.mClickImageForPlayTime);
        }

//        playStateableHandler.onResume();


//        EventBus.getDefault().post(new FetchMetaEvent());

    }

    @Override
    protected void onPause() {
        super.onPause();
        mPlayAdController.pause();
        mAlbumPlayFragment.onPause();
        mAlbumPlayFragment.callAdsPlayInterface(AlbumPlayFragment.ON_ACTIVITY_PAUSE, false);

        playStateableHandler.onPause();

    }

    @Override
    protected void onStop() {
        super.onStop();
        UIsUtils.disableScreenAlwaysOn(this);
        if (mPlayAlbumFlow != null && !mPlayAlbumFlow.isAdFinished()) {
            // 上报动作22
            if (mPlayAlbumFlow.getPlayInfo().mTotalConsumeTime != 0) {
                mPlayAlbumFlow.getPlayInfo().mTotalConsumeTime =
                        mPlayAdController.getAdFragment().getAdsPlayFirstFrameTime() -
                                mPlayAlbumFlow.getPlayInfo().mTotalConsumeTime;
                PlayStatisticsUtils.staticticsLoadTimeInfo(this, mPlayAlbumFlow, mPlayAdController.getAdFragment());
            }
        }
        mPlayAdController.pause();
        mAlbumPlayFragment.pause();
        mAlbumPlayFragment.pauseCde();
        mController.onDestory();
        if (mPlayAlbumFlow != null && mAlbumPlayFragment.getPlayingHandler() != null) {
            mPlayAlbumFlow.getPlayInfo().mGlsbNum += 1;
            mAlbumPlayFragment.getPlayingHandler().stopHandlerTime();
            mAlbumPlayFragment.getPlayingHandler().onStopBack();
        }


    }

    /**
     * 初始化M站信息
     */
    private void initMParams() {
        StatisticsUtils.setStartType("");
        AlbumLaunchUtils.initMParams(this, getIntent());
    }

    /**
     * 从intent中获取数据
     * <p>
     * 除了相关视频  视频播放时都是先缓存再请求数据
     */
    private void initDataFromIntent(Intent intent) {
        if (intent == null || intent.getExtras() == null) {
            return;
        }
        mFromPushMsg = intent.getBooleanExtra(ConstantUtil.FROM_PUSH_MSG, false);
        if (mFromPushMsg) {
            int pushMsgCount = LedimSpUtils.getPushMgsCount();
            if (pushMsgCount > 0) {
                pushMsgCount--;
                LedimSpUtils.setPushMgsCount(pushMsgCount);
            }
        }
        //得到从LetvSDK.getInstance().play()传过来的CARD对象
        mCard = (LedimChoiceCardBean) intent.getSerializableExtra(PlayConstant.CARD);

        mIsLoadData = intent.getBooleanExtra(PlayConstant.IS_LOAD_DATA, true);
        if (mIsLoadData) {
            /**
             * 读取历史记录
             */
            LedimChoiceCardBean card = LedimDBUtils.queryChoiceCard(mCard);
            if (card != null) {
                mCard = card;
            } else {
                if (!TextUtils.isEmpty(mCard.link))
                {
                    String link = mCard.link.replace("app://medias/", "");
                    String[] s = link.split("/");
                    if (s.length > 1)
                    {
                        mCard.media = s[0];
                        mCard.submedia = s[1];
                    }
                }
            }
        }
        String duration =
                mCard.video == null || mCard.video.duration == null ? mCard.playedDuration + ""
                                                                    : mCard.video.duration;
        mTabsFragment =
                TabsFragment.getInstance(mCard.title, duration, mCard.media, mCard.submedia);

        setVid(Integer.valueOf(mCard.submedia), mCard.playedDuration);
        mLaunchMode = intent.getIntExtra(PlayConstant.LAUNCH_MODE, 0);
        mIs4dVideo = !TextUtils.isEmpty(getIntent().getStringExtra(PlayConstant.HAPT_URL));

        if (mLaunchMode == 0) {
            String path = null;
            if (null != intent && null != intent.getData()) {
                Uri uriPath = intent.getData();
                String scheme = uriPath.getScheme();
                if (scheme == null || scheme.equals("file")) {
                    path = uriPath.getPath();
                } else {
                    path = uriPath.toString();
                }
            }
            mLaunchMode = PlayConstant.LAUNCH_MODE_URI;
            intent.putExtra(PlayConstant.LAUNCH_MODE, PlayConstant.LAUNCH_MODE_URI);
            intent.putExtra(PlayConstant.URI, path);
            intent.putExtra(PlayConstant.SEEK, 0);
            intent.putExtra(PlayConstant.PLAY_MODE, PlayConstant.PLAY_MODE_SYSTEM);
        }
    }

    private void init() {
        mTabsFragment.setActivity(this);
        mBottomFrame = getViewById(R.id.play_album_bottom_frame);
        mFloatFrame = getViewById(R.id.layout_album_float_frame);
        getViewById(R.id.play_album_full_episode).getLayoutParams().width =
                UIsUtils.dipToPx(this, 283);

        mAlbumPlayFragment = new AlbumPlayFragment(this);
        mHalfControllerFragment =
                new AlbumHalfControllerFragment(this, getViewById(R.id.player_half_controller_contain));
        mFullControllerFragment =
                new AlbumFullControllerFragment(this, getViewById(R.id.player_full_controller_contain));

        mPlayObservable = new PlayObservable(this);
        playAlbumController = new PlayAlbumController(this);

        mVideoControllerMeditor =
                new VideoControllerMeditor(mHalfControllerFragment, mFullControllerFragment, mAlbumPlayFragment);
        mAlbumPlayFragment.setControllerMeditor(mVideoControllerMeditor);
        mHalfControllerFragment.setMeditor(mVideoControllerMeditor);
        mFullControllerFragment.setMeditor(mVideoControllerMeditor);

        mGestureController =
                new AlbumGestureController(this, mAlbumPlayFragment, mGestureObservable);
        mPlayAdController = new AlbumPlayAdController(this);
        mVipTrailController = new AlbumPlayVipTrailController(this);

        mController = new AlbumController(this);
        mController.initDefaultSensor(); // 初始化陀螺仪

        mTopController = new AlbumErrorTopController(this);
        mNetChangeController = new AlbumNetChangeController(this);
        mRecommendController = new AlbumRecommendController(this);
        mLongWatchController = new LongWatchController(this);
        mLoadController = new AlbumLoadController(this, mBottomFrame);
        mLoadController.setOnBlockCallBack(mFullControllerFragment);

        AlbumPlayContainView parentView = getViewById(R.id.play_album_parent_view);
        parentView.setLongWatchController(mLongWatchController);
        getSupportFragmentManager().beginTransaction()
                                   .add(R.id.play_album_ad_contain, mPlayAdController.getAdFragment())
                                   .commitAllowingStateLoss();

        addObserverToScreenObservable();
        addObserverToFlowObservable();
        addObserverToPlayObservable();
        addObserverToGestureObservable();

        initWithIntent(getIntent());
    }

    private void initWithIntent(Intent intent) {
        if (intent == null || intent.getExtras() == null) {
            return;
        }

        mAlbumPlayFragment.setIntent(intent);

        mFullControllerFragment.setLaunchMode(mLaunchMode);
        mFullControllerFragment.setIs4d(mIs4dVideo);

        boolean isDolby = intent.getExtras().getBoolean(PlayConstant.IS_DOLBY);
        mPlayAdController.setLaunchMode(mLaunchMode, mIs4dVideo, isDolby);
        if (isDolby) {
            mTopController.setVisibilityForSwitchView(View.GONE);
        }

        if (mLaunchMode == PlayConstant.LAUNCH_MODE_VIDEO || mIs4dVideo ||
                mLaunchMode == PlayConstant.LAUNCH_MODE_URI) {
            mController.fullLock();
        }

        mFullControllerFragment.initFullState();

    }

    /**
     * 给点播流程观察者添加对象
     */
    private void addObserverToScreenObservable() {
        mScreenObservable.addObserver(mAlbumPlayFragment);
        mScreenObservable.addObserver(mHalfControllerFragment);
        mScreenObservable.addObserver(mFullControllerFragment);
        mScreenObservable.addObserver(mTabsFragment);
        mScreenObservable.addObserver(mRecommendController);
    }

    /**
     * 给点播流程观察者添加对象
     */
    private void addObserverToFlowObservable() {
        mFlowObservable.addObserver(mAlbumPlayFragment);
        mFlowObservable.addObserver(mHalfControllerFragment);
        mFlowObservable.addObserver(mFullControllerFragment);
        mFlowObservable.addObserver(mGestureController);
        mFlowObservable.addObserver(mTabsFragment);
        mFlowObservable.addObserver(mNetChangeController);
        mFlowObservable.addObserver(mTopController);
    }

    /**
     * 给播放观察者添加对象
     */
    private void addObserverToPlayObservable() {
        mPlayObservable.addObserver(mAlbumPlayFragment);
        mPlayObservable.addObserver(mHalfControllerFragment);
        mPlayObservable.addObserver(mFullControllerFragment);
        //        mPlayObservable.addObserver(mTabsFragment);

        // 初始化手势控制器
        mPlayObservable.addObserver(mGestureController);
        // 网络错误控制器
        mPlayObservable.addObserver(mNetChangeController);
        // 错误时上层布局控制器
        mPlayObservable.addObserver(mTopController);
    }

    /**
     * 给手势观察者添加对象
     */
    private void addObserverToGestureObservable() {
        mGestureObservable.addObserver(mAlbumPlayFragment);
        mGestureObservable.addObserver(mHalfControllerFragment);
        mGestureObservable.addObserver(mFullControllerFragment);
        mGestureObservable.addObserver(mGestureController);
    }

    private void initFragments() {

        addFragments(mTabsFragment);
    }

    /**
     * 初始化横竖屏状态
     */
    private void initWindow() {
        boolean isLandscape = UIsUtils.isLandscape(this);
        if (isLandscape) {
            // SDK 横屏
            InputMethodManager manager =
                    (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
            UIsUtils.zoomViewFull(this, mBottomFrame);
            UIsUtils.zoomViewFull(this, mFloatFrame);
            UIsUtils.fullScreen(this);
            mHalfControllerFragment.isHalf(false);
            mFullControllerFragment.isFull(true);
        } else {
            UIsUtils.zoomView(this, 320, 180, mBottomFrame);
            UIsUtils.zoomView(this, 320, 180, mFloatFrame);
            UIsUtils.cancelFullScreen(this);
            mHalfControllerFragment.isHalf(true);
            mFullControllerFragment.isFull(false);
        }
        mScreenObservable.notifyObservers(ScreenObservable.ON_CONFIG_CHANGE);
    }

    /**
     * 开始执行业务流程
     */
    public void startFlow(Intent intent) {
        if (intent != null && intent.getExtras() != null &&
                intent.getIntExtra(PlayConstant.VID, 0) != 0) {
            mPlayAlbumFlow = AlbumFlowUtils.getPlayFlow(this, mLaunchMode, intent.getExtras());

            if (mPlayAlbumFlow != null) {
                playStateableHandler.onResume();

                mPlayObservable.addObserver(mPlayAlbumFlow);
                //点播流程设置点播流程观察者对象
                mPlayAlbumFlow.setObservable(mFlowObservable);
                mPlayAlbumFlow.setLoadListener(mLoadController);
                mPlayAlbumFlow.setAdListener(mPlayAdController);
                mPlayAlbumFlow.setVideoListener(mAlbumPlayFragment);
                mPlayAlbumFlow.setAlbumPlayingListener(playAlbumController);
                mPlayAlbumFlow.start();

            }
        }
    }

    /**
     * 设置Vid
     *
     * @param vid
     */
    public void setVid(int vid, long time) {
        if (mPlayAlbumFlow != null) {
            mPlayAlbumFlow.format();
        }
        if (LetvSDK.getInstance().getmVideo() != null) {
            LetvSDK.getInstance().getmVideo().setmCurrentTime(time);
        }
        getIntent().putExtra(PlayConstant.VID, vid);
        mPlayAlbumFlow = AlbumFlowUtils.getPlayFlow(this, mLaunchMode, getIntent().getExtras());
        if (mPlayAlbumFlow != null) {
            playStateableHandler.onResume();

            mPlayObservable.addObserver(mPlayAlbumFlow);
            //点播流程设置点播流程观察者对象
            mPlayAlbumFlow.setObservable(mFlowObservable);
            mPlayAlbumFlow.setLoadListener(mLoadController);
            mPlayAlbumFlow.setAdListener(mPlayAdController);
            mPlayAlbumFlow.setVideoListener(mAlbumPlayFragment);
            mPlayAlbumFlow.setAlbumPlayingListener(playAlbumController);
            mPlayAlbumFlow.start();
            mHasStartFlowOnStart = true;

        }
    }

    public void setData(ArrayList<LedimEpisodeBean> data) {
        mFullControllerFragment.setEpisode(data);
    }

    // 播放上一集
    public void playerLast() {
        if (mPlayAlbumFlow != null && mPlayAlbumFlow.getPlayRecord() != null) {
            mTabsFragment.refreshLast(mPlayAlbumFlow.getPlayRecord().getVideoId());
        }
    }

    // 播放下一集
    public void finishPlayer() {
        if (mPlayAlbumFlow != null && mPlayAlbumFlow.getPlayRecord() != null) {
            mTabsFragment.refreshNext(mPlayAlbumFlow.getPlayRecord().getVideoId());
        }
    }

    // 加载时不显示播放暂停按钮
    public void setLoadStatus(boolean show) {
        mHalfControllerFragment.showLoad(show);
        mFullControllerFragment.showLoad(show);
    }

    //亮度提示框
    public void showBrightness() {
        mHalfControllerFragment.showBrightness();
        mFullControllerFragment.showBrightness();
    }

    //进度提示框
    public void showSeekProgress() {
        mHalfControllerFragment.showSeekProgress();
        mFullControllerFragment.showSeekProgress();
    }

    //声音提示框
    public void showVolume() {
        mHalfControllerFragment.showVolume();
        mFullControllerFragment.showVolume();
    }

    //隐藏提示框
    public void hideLayout() {
        mHalfControllerFragment.hideLayout();
        mFullControllerFragment.hideLayout();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initWindow();// 旋转后更改页面尺寸
    }

    // ---------------- 获取fragment实例 ----------------

    public AlbumPlayFragment getAlbumPlayFragment() {
        return mAlbumPlayFragment;
    }

    public AlbumFullControllerFragment getFullControllerFragment() {
        return mFullControllerFragment;
    }

    public AlbumHalfControllerFragment getHalfControllerFragment() {
        return mHalfControllerFragment;
    }

    /**
     * 获取业务流程
     * <p>
     * 响应使用flow,每次必须通过这个方法获取
     *
     * @return
     */
    public AlbumPlayFlow getFlow() {
        //        mPlayAlbumFlow.setSkip(false);
        return mPlayAlbumFlow;
    }

    /**
     * 获取状态机Handle
     *
     * @return
     */

    public PlayStateableHandler getPlayStateableHandler() {
        return playStateableHandler;
    }

    /**
     * 获取当前正在播放video
     *
     * @return
     */
    public VideoBean getPlayingVideoBean() {
        return null != mPlayAlbumFlow ? mPlayAlbumFlow.getPlayingVideo() : null;
    }

    // ---------------- 获取observable实例 ----------------

    /**
     * 获取播放观察者
     *
     * @return
     */
    public PlayObservable getPlayObservable() {
        return mPlayObservable;
    }

    /**
     * 获取手势观察者
     *
     * @return
     */
    public AlbumGestureObservable getGestureObservable() {
        return mGestureObservable;
    }

    /**
     * 获取AlbumLoadController对外暴露的接口
     *
     * @return
     */
    public AlbumLoadController getLoadListener() {
        return mLoadController;
    }

    /**
     * 获取试看接口
     *
     * @return
     */
    public AlbumPlayVipTrailController getVipTrailListener() {
        return mVipTrailController;
    }

    /**
     * 获取手势控制器
     *
     * @return
     */
    public AlbumGestureController getGestureController() {
        return mGestureController;
    }

    /**
     * 获取控制器
     *
     * @return
     */
    public AlbumController getController() {
        return mController;
    }

    public PlayAlbumController getPlayAlbumController() {
        return playAlbumController;
    }

    public AlbumNetChangeController getNetChangeController() {
        return mNetChangeController;
    }

    public AlbumErrorTopController getErrorTopController() {
        return mTopController;
    }

    public AlbumRecommendController getRecommendController() {
        return mRecommendController;
    }

    public LongWatchController getLongWatchController() {
        return mLongWatchController;
    }

    /**
     * 获取广告工具类
     *
     * @return
     */
    public AlbumPlayAdController getPlayAdListener() {
        return mPlayAdController;
    }

    private void clearObservables() {
        if (mScreenObservable != null) {
            mScreenObservable.deleteObservers();
        }
        if (mFlowObservable != null) {
            mFlowObservable.deleteObservers();
        }
        if (mPlayObservable != null) {
            mPlayObservable.deleteObservers();
        }
        if (mGestureObservable != null) {
            mGestureObservable.deleteObservers();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //视频播放页面的剧集显示与否
            if (mAlbumsLayout != null && mAlbumsLayout.getVisibility() == View.VISIBLE) {
                mAlbumsLayout.setVisibility(View.GONE);
                mButtonLayout.setVisibility(View.VISIBLE);
            } else if (mAddTagLayout != null && mAddTagLayout.getVisibility() == View.VISIBLE) {
                mAddTagLayout.setVisibility(View.GONE);
                mButtonLayout.setVisibility(View.VISIBLE);
            } else {
                boolean isLandscape = UIsUtils.isLandscape(this);
                if (isLandscape) {
                    mController.half();
                } else {
                    if (mPlayAlbumFlow == null) {
                        upToHome();
                        finish();
                        return true;
                    } else {
                        if (mLaunchMode == PlayConstant.LAUNCH_MODE_VIDEO || mIs4dVideo ||
                                mLaunchMode == PlayConstant.LAUNCH_MODE_URI) {
                            mController.back();
                            upToHome();
                            return true;
                        } else {
                            // 其他半屏
                            mController.back();
                            upToHome();
                            return true;
                        }
                    }
                }

            }
        }

        return false;
    }

    public void upToHome() {
        if (mFromPushMsg && MainActivity.getInstance() == null) {
            upToHome(MainActivity.class, null);
        }
    }

    /**
     * 上报最后一次心跳
     */
    public void reportLastHeartEvent() {
        LogUtil.e("ccx reportEvent reportLastHeartEvent");
        AlbumPlayInfo mPlayInfo;
        if ((mPlayInfo = mPlayAlbumFlow.getPlayInfo()) != null) {
            long elapsedDiff = mPlayInfo.timeElapsed - mPlayInfo.lastTimeElapsed;
            if (elapsedDiff > 0) {
                sendHeartEvent((int) elapsedDiff);
            }
        }
    }

    /**
     * 大数据上传cancel
     */
    public void reportPlayCancelEvent() {

        if (mPlayAlbumFlow == null) {
            return;
        }
        if (mHalfControllerFragment != null && mHalfControllerFragment.getmSeekBar() != null) {
            if (mHalfControllerFragment.getmSeekBar().getProgress() > 0 &&
                    mHalfControllerFragment.getmSeekBar().getProgress() != 100) {
                VideoPlay videoPlay = mPlayAlbumFlow.getCommonVideoPlay();
                videoPlay.cancel(mHalfControllerFragment.getmSeekBar().getProgress());
                LogUtil.e("ccx reportEvent reportPlayCancelEvent play id=" + videoPlay.getId());
                LeDimAnalysisUtils.reportPlayEvent(videoPlay);
            }
        }

    }

    /**
     * 大数据上传finish
     */
    public void reportPlayFinishEvent() {
        LogUtil.e("reportPlayCancelEvent");
        if (mPlayAlbumFlow == null) {
            return;
        }
        VideoPlay videoPlay = mPlayAlbumFlow.getCommonVideoPlay();
        videoPlay.finish();
        LeDimAnalysisUtils.reportPlayEvent(videoPlay);

    }

    /**
     * @param time
     *         大数据上传心跳 ccx
     */
    public void sendHeartEvent(int time) {
        if (mPlayAlbumFlow == null) {
            return;
        }
        VideoPlay videoPlay = mPlayAlbumFlow.getCommonVideoPlay();
        int progress = 0;
        if (UIsUtils.isLandscape(this)) {
            if (mFullControllerFragment != null) {
                progress = mFullControllerFragment.getmSeekBar().getProgress();
            }
        } else {
            if (mHalfControllerFragment != null) {
                progress = mHalfControllerFragment.getmSeekBar().getProgress();
            }
        }
        videoPlay.sendHeartbeat(progress, time);
        LogUtil.e("ccx sendHeartEvent time==" + time+",systemTine=="+System.currentTimeMillis()
                +",actionTime==");

        LogUtil.e("ccx reportEvent sendHeartEvent playid==" + videoPlay.getId());
        LeDimAnalysisUtils.reportPlayEvent(videoPlay);
    }

    @Override
    public void finish() {
        super.finish();
        /**
         * 卡片保存本地，含播放时间和当前剧集
         */
        if (mCard != null && mCard.link != null && mCard.link.length() > 0) {
            String link = mCard.link.replace("app://medias/", "");
            String[] s = link.split("/");

            if (s.length > 1 && mPlayAlbumFlow != null && mPlayAlbumFlow.getPlayRecord() != null) {
                //if(mPlayAlbumFlow.getPlayRecord().getChannelId() == ENUM_CHANNEL_TYPE.TV.value()
                //        || mPlayAlbumFlow.getPlayRecord().getChannelId() == ENUM_CHANNEL_TYPE.CARTOON.value()
                //        || mPlayAlbumFlow.getPlayRecord().getChannelId() == ENUM_CHANNEL_TYPE.USTV.value()
                //        || mPlayAlbumFlow.getPlayRecord().getChannelId() == ENUM_CHANNEL_TYPE.RECORD.value()
                //        || mPlayAlbumFlow.getPlayRecord().getChannelId() == ENUM_CHANNEL_TYPE.VARIETY.value()
                //        || mPlayAlbumFlow.getPlayRecord().getChannelId() == ENUM_CHANNEL_TYPE.SELF.value()) {
                //    mCard.media = s[0];
                //} else {
                //    mCard.media = s[0] + "-" + mPlayAlbumFlow.getPlayRecord().getVideoId();
                //    mCard.photo.thumb = mPlayAlbumFlow.getPlayRecord().getImg();
                //    mCard.photo.large = mPlayAlbumFlow.getPlayRecord().getImg();
                //}
                mCard.media = s[0];
                mCard.submedia = mPlayAlbumFlow.getPlayRecord().getVideoId() + "";
                mCard.playedDuration = mPlayAlbumFlow.getPlayRecord().getPlayedDuration() * 1000;
                if (mTabsFragment.getCurrentEpisode() != null) {
                    showTitleName(mTabsFragment.getCurrentEpisode());
                }
                mCard.time = System.currentTimeMillis();
                try {
                    LedimDBUtils.saveChoiceCard(mCard);
                }catch (Exception e){
                    LogUtil.e("ccx save card failed err="+e.getMessage());
                }

            }
        }

        Volley.getQueue().cancelAll(new RequestFilter() {

            @Override
            public boolean apply(VolleyRequest<?> request) {
                return request != null && !TextUtils.isEmpty(request.getTag()) &&
                        request.getTag().startsWith(AlbumPlayFlow.ALBUM_FLOW_TAG);
            }
        });

        if (TextUtils.equals("Coolpad_T2-00", LetvUtils.getModelName())) {
            format();
        }
        // overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    //显示剧集的类型
    private void showTitleName(LedimEpisodeBean episode) {
        if (episode.nameCn != null && episode.nameCn.length() > 0) {
            mCard.nameCn = episode.nameCn;
        } else if (episode.subTitle != null && episode.subTitle.length() > 0) {
            mCard.nameCn = episode.subTitle;
        }
        if (!episode.videoType.equals("{}")) {
            switch (episode.getVedioType()) {
                case POSITIVE://正片
                case TV:
                    if (episode.getcategory() == ConstantUtil.ChannelType.variety) {//综艺
                        getPlayEpisode(episode);
                    } else if (episode.getcategory() == ConstantUtil.ChannelType.tv ||
                            episode.getcategory() == ConstantUtil.ChannelType.cartoon) {//电视剧
                        mCard.playedEpisode = episode.episode + "集";
                    } else {
                        getPlayEpisode(episode);
                    }
                    break;
                default:
                    getPlayEpisode(episode);
                    break;
            }
        }
    }

    //得到播放剧集
    private void getPlayEpisode(LedimEpisodeBean episode) {
        String str = episode.episode;
        if (str.length() == 8) {
            String episode1 = str.substring(0, 4);
            String episode2 = str.substring(4, 6);
            String episode3 = str.substring(6, str.length());
            mCard.playedEpisode = episode1 + "-" + episode2 + "-" + episode3 + "期";
        } else {
            mCard.playedEpisode = str;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (!TextUtils.equals("Coolpad_T2-00", LetvUtils.getModelName())) {
            format();
        }

        AlbumBaseControllerFragment.sShowingWhenSwitch = true;

        /** 用户如果不是手动的点击暂停，那么就不要有广告的弹出 **/
        sIsBlockPause = false;
        sIsFromDownload = false;
        sIsFromCollection = false;
        sIsFromDobiChannel = false;

//        EventBus.getDefault().unregister(this);

    }

    private void format() {
        if (mLongWatchController != null) {
            mLongWatchController.onDestory();
        }
        if (mLoadController != null) {
            mLoadController.onDestory();
        }

        mAlbumPlayFragment.onDestroy();
        mAlbumPlayFragment.callAdsPlayInterface(AlbumPlayFragment.ON_ACTIVITY_EXIT, false);

        mFullControllerFragment.onDestroy();
        mHalfControllerFragment.onDestroy();

        mController.onDestory();

        clearObservables();
        sIsShowingLongwatch = false;
        if (mFinishSelf != null) {
            unregisterReceiver(mFinishSelf);
        }
        //退出播放，SDK需要重新初始化
        LetvSDK.getInstance().setIsInited(false);
        mGestureController.onDestroy();
    }

    @Override
    public String[] getAllFragmentTags() {
        return FragmentConstant.ALBUM_FRAGMENT_TAG_ARRAY;
    }

    @Override
    public String getActivityName() {
        return AlbumPlayActivity.class.getName();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (getFlow() != null && getFlow().getPlayRecord() != null) {
                LetvSDK.getInstance()
                        .getmVideo()
                        .setmCurrentTime(getFlow().getPlayRecord().getPlayedDuration());
                getIntent().putExtra(PlayConstant.VID, getFlow().getPlayRecord().getVideoId());
                getFlow().start();
            }
        }
    }
}
